package com.coderxq.blog.config;

import com.alibaba.druid.util.StringUtils;

import com.coderxq.blog.annotation.RequestAnnotation;
import com.coderxq.blog.exception.WsException;
import com.coderxq.blog.utils.ResponseResult;
import com.coderxq.blog.utils.jwt.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.spi.ServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author: lijingming
 * @Date: 2025/1/9
 * @Description:
 **/
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //这一步判断接受处理的方法是不是属于spring mvc的请求处理方法 (带有 @RequestMapping、@GetMapping、@PostMapping 等注解的方法。或者@PutMapping、@DeleteMapping ) ,
        // 当处理方法为spring管理的请求处理方法时 说明该方法所处的类被spring的@Controller注解修饰
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();//获取该处理方法所在的类的class
            final Method method = handlerMethod.getMethod();

            if (clazz.isAnnotationPresent(RequestAnnotation.class)) { //判断该类上是否存在该@RequestAnnotation 注解
                //request.setAttribute(RESPONSE_ANNOTATION, clazz.getAnnotation(RequestAnnotation.class));
            } else if (method.isAnnotationPresent(RequestAnnotation.class)) {
                //request.setAttribute(RESPONSE_ANNOTATION, method.getAnnotation(RequestAnnotation.class));
            }
        }



        // 获取请求头中令牌
        String token = request.getHeader("Authorization");
        log.info("request:"+request.getRequestURI());

        // 判断令牌是否存在，如果不存在则抛出异常
        if (StringUtils.isEmpty(token)) {
            throw new WsException("未登录");
        }
        if(!JwtUtil.verifyToken(token)){
            throw new WsException("token失效");
        }
        return true;
    }



}
